package eddy.yang.wordpad;
import java.awt.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.*;

class TextSaver extends Thread {
   Document doc;
   File f;

	TextSaver(File f, Document doc) {
	   setPriority(4);
	   this.f = f;
	   this.doc = doc;
	}

   public void run() {
	   try {
		   // initialize the statusbar
		   JProgressBar progress = new JProgressBar();
		   progress.setMinimum(0);
		   progress.setMaximum((int) doc.getLength());
         
		   // start writing
		   Writer out = new FileWriter(f);
         Segment text = new Segment();
         text.setPartialReturn(true);
         int charsLeft = doc.getLength();
		   int offset = 0;
         while (charsLeft > 0) {
            doc.getText(offset, Math.min(4096, charsLeft), text);
            out.write(text.array, text.offset, text.count);
            charsLeft -= text.count;
            offset += text.count;
            progress.setValue(offset);
            try {
               Thread.sleep(10);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }
         out.flush();
         out.close();
	   }
	   catch (IOException e) {
         final String msg = e.getMessage();
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               JOptionPane.showMessageDialog(null,
                       "Could not save file: " + msg,
                       "Error saving file",
                       JOptionPane.ERROR_MESSAGE);
	   		 }
         });
	   }
	   catch (BadLocationException e) {
			System.err.println(e.getMessage());
		}
	}
}